//package src;
import javax.swing.*; 
import javax.swing.event.MouseInputListener;
import java.awt.*; 
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.util.Vector;

public class LinearGUI extends JFrame implements ActionListener
{ 

// MAIN MENU 
private JMenuBar MainMenu; 
private JMenu fileMenu; 
private JMenuItem file_newItem; 
private JMenuItem file_openItem; 
private JMenuItem file_saveAsItem; 
private JMenuItem file_exitItem; 
private static final long serialVersionUID = 1L; 
final JFileChooser fc = new JFileChooser(); 

// SIDE MENU 
private JMenuBar SideMenu; 
private JMenu rectangles; 
private JMenu triangles; 
private JMenu circle; 
private JMenu lines; 
private JMenu alpha; 
private JMenu digit; 
private JMenu misc; 
private JMenu custom; 
private JMenuItem rectangle1; 
private JMenuItem rectangle2; 
private JMenuItem triangles1; 
private JMenuItem triangles2; 
private JMenuItem circle1; 
private JMenuItem circle2; 
private JMenuItem lines1; 
private JMenuItem lines2; 
private JMenuItem alpha1; 
private JMenuItem alpha2; 
private JMenuItem digit1; 
private JMenuItem digit2; 
private JMenuItem misc1; 
private JMenuItem misc2; 
private JMenuItem custom1; 
private JMenuItem custom2; 
private Drawing Layer;
private EventHandler eventhandle;
private static Order ordering; 
private final Color firstColor = Color.BLACK;
Color ColorDesign = new Color(232,232,233);
public CustomPanel DrawPanel;
private Pointlocation pointlocation;
public int drawingStyle;
private JLabel helptext;
private JFileChooser fileChoose = new JFileChooser();
private String fileName = "defalt.lgu";
private File saveFile;


Graphics2D graphics2D;

public GraphicsObject object1 = new GraphicsObject();

final PadDraw drawPad = new PadDraw(drawingStyle, graphics2D);  // Initializes the rightmost panel which will be the interactive drawing pad


private void saveFile(String filename, String infoStr)
{
	try
	{
		PrintWriter outputfile = new PrintWriter(new FileWriter(filename));
		outputfile.println(infoStr);
		outputfile.close();
		
	}
	catch (Exception e)
	{
		JOptionPane.showMessageDialog(this, "The file could not be saved.", "IO Error", JOptionPane.WARNING_MESSAGE);
		File fl = new File(filename);
		try
		{
			setName("");
			
			fl.delete();
		} catch (Exception delex) {}
	}
}


public String getString()
{
	
	String temporary = object1.objectToString();
	
	
	return temporary;
}



public void mouseClicked(MouseEvent e) 
{ 
	PointerInfo a = MouseInfo.getPointerInfo(); 
	Point point = new Point(a.getLocation()); 
	SwingUtilities.convertPointFromScreen(point, e.getComponent()); 
} 

private void onFileNew()
{
	Point2D.Double a = new Point2D.Double();
	Point2D.Double b = new Point2D.Double();
	Point2D.Double c = new Point2D.Double();
	Point2D.Double d = new Point2D.Double();


	a.setLocation(10, 10);
	b.setLocation(10, 500);
	c.setLocation(500, 10);
	d.setLocation(500, 500);

	GraphicsObject test = new GraphicsObject();
	test.addPoint(a);
	test.addPoint(b);
	test.addPoint(c);
	test.addPoint(d);

    test.draw(drawPad);

	
	
	
	/*
	for(int i = 0; i < object1.getNumPoints(); i++)
	{
		object1.displayPoint(i);
	}
	object1.objectToString();
	*/
}

/*
private void onFileOpen() 
{ 
//String[] PGDfiles = new String[] {"lin"}; 
//String filename = ""; 
	String[] PGDfiles = new String[] {"lgu"}; 
	String filename = ""; 
	JFileChooser fc = new JFileChooser(); 
	fc.addChoosableFileFilter(new SimpleFileFilter(PGDfiles, "Linear Gui Files (*.lgu)"));
	int option = fc.showOpenDialog(this); 
	if (option == JFileChooser.APPROVE_OPTION)
	{
		if (fc.getSelectedFile() != null)
			filename = fc.getSelectedFile().getPath();
	}
	else
		return;

	try
	{
		String InStr = "";
		BufferedReader br = new BufferedReader(new FileReader(filename));			
		InStr = br.readLine();
		br.close();
		object1.stringToObject(InStr, drawPad);
		//System.out.println(InStr);
	}
	catch(Exception ioex)
	{
		JOptionPane.showMessageDialog(this, "THIS FILE COULD NOT BE OPENED.", "IO ERROR", JOptionPane.WARNING_MESSAGE);
	}
}


private void onFileSaveAs() 
{
//String[] PGDfiles = new String[] {"lin"}; 
//String filename = ""; 
	String[] LinearGuiFiles = new String[] {"lin"};
	JFileChooser fc = new JFileChooser(); 
	fc.addChoosableFileFilter(new SimpleFileFilter(LinearGuiFiles, "Linear GUI Document Files (*.lgu)"));
	int option = fc.showSaveDialog(this); 

	if (option == JFileChooser.APPROVE_OPTION)
	{
		if (fc.getSelectedFile() != null)	
		{
			String filename = fc.getSelectedFile().getPath();
			filename = filename.trim();
			if (!filename.toLowerCase().endsWith(".lgu"))
				filename = filename + ".lgu";

			boolean okToSave = true;
			/*
			if (FileExists(filename))
			{
				okToSave = false;
				int ans = JOptionPane.showConfirmDialog(this, "The file " + filename + " already exists. \nDo you wish to overwrite the file?", "Overwrite File", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				if (ans == JOptionPane.YES_OPTION)
					okToSave = true;
			}
	        */
			/*
			if (okToSave)
			{
				String infoStr = "~~~~~ Linear ME User Defined Graphics Utility ~~~~~";
				infoStr = infoStr + getString();
				System.out.println(infoStr);
				saveFile(filename, infoStr);
				System.out.println(getString());
			}
		}
	}
} 
*/

private void onFileOpen() 
{
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		
		fc.showOpenDialog(this);
		
		File file = fc.getSelectedFile();
		
		try
		{	
		ObjectInputStream open = new ObjectInputStream(new FileInputStream(file));
		Vector newobject = (Vector) open.readObject();
		Layer.setDrawing(newobject);
		open.close();
		repaint();
		
		} 
		catch (Exception e) { System.out.println(e); }
}

private void onFileSaveAs()
{
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		
		fc.showSaveDialog(this);
			
		File file = fc.getSelectedFile();
		
		try
		{
		ObjectOutputStream save = new ObjectOutputStream(new FileOutputStream(file));
		save.writeObject(Layer.getDrawing());
		save.close();
		}
		catch (Exception e) { System.out.println(e); }		
	
}

private void createMenu()
{

        MainMenu = new JMenuBar();
        fileMenu = new JMenu("File");
        
        file_newItem = new JMenuItem("New", new ImageIcon("image/FileNewImage.GIF"));
		file_newItem.setMnemonic('N');
		file_openItem = new JMenuItem("Open", new ImageIcon("image/FileOpenImage.GIF"));
		file_openItem.setMnemonic('O');
        file_openItem.addActionListener(new ActionListener()
        {       public void actionPerformed(ActionEvent evt) 
        { onFileOpen(); }}
        );
        
        file_saveAsItem = new JMenuItem("Save As", new ImageIcon("image/FileSaveAsImage.GIF"));
		file_saveAsItem.setMnemonic('S');
        
        file_saveAsItem.addActionListener(new ActionListener()
        {       public void actionPerformed(ActionEvent evt) 
        { onFileSaveAs(); }}
        );
        
        file_exitItem = new JMenuItem("Exit", 'X');
        
        file_exitItem.addActionListener(new ActionListener()
        {       public void actionPerformed(ActionEvent evt) 
        { System.exit(0); }}
        );
        
        fileMenu.add(file_newItem);
        fileMenu.add(file_openItem);
        fileMenu.add(file_saveAsItem);
        fileMenu.add(file_exitItem);
        
        MainMenu.add(fileMenu);
}

private void createSideMenu() 
{ 
	Dimension IconSize = new Dimension(40,77);
	SideMenu = new JMenuBar(); 
	SideMenu.setLayout(new BoxLayout(SideMenu, BoxLayout.Y_AXIS)); 
	rectangles = new HorizontalMenu("");
	rectangles.setIcon(new ImageIcon("image/rectangle.gif"));
	rectangles.setPreferredSize(IconSize);
	
	triangles = new HorizontalMenu("");
	triangles.setIcon(new ImageIcon("image/triangle.gif"));
	triangles.setPreferredSize(IconSize);

	circle = new HorizontalMenu(""); 
	circle.setIcon(new ImageIcon("image/circle.gif"));
	circle.setPreferredSize(IconSize);
	
	lines = new HorizontalMenu(""); 
	lines.setIcon(new ImageIcon("image/line.gif"));
	lines.setPreferredSize(IconSize);
	
	alpha = new HorizontalMenu(""); 
	alpha.setIcon(new ImageIcon("image/letter.gif"));
	alpha.setPreferredSize(IconSize);
	
	digit = new HorizontalMenu(""); 
	digit.setIcon(new ImageIcon("image/number.gif"));
	digit.setPreferredSize(IconSize);
	
	misc = new HorizontalMenu(""); 
	misc.setIcon(new ImageIcon("image/misc.gif"));
	misc.setPreferredSize(IconSize);
	
	custom = new HorizontalMenu(""); 
	custom.setIcon(new ImageIcon("image/custom.gif"));
	custom.setPreferredSize(IconSize);
	
	rectangle1 = new JMenuItem("Open Rectangle");
	rectangle1.addActionListener(eventhandle);
	rectangle1.setActionCommand("13");
	rectangle1.addMouseMotionListener(new MouseMotionAdapter(){});
    
    
    
    rectangle2 = new JMenuItem("Solid Rectangle");
    rectangle2.addActionListener(new ActionListener()
    {     public void actionPerformed(ActionEvent evt)
    { drawingStyle = 2;
      drawPad.setDStyle(drawingStyle);}}
    );
    triangles1 = new JMenuItem("Triangle 1");
    triangles2 = new JMenuItem("Triangle 2");
    

    
 
    circle1 = new JMenuItem("Open Oval");
    circle1.addActionListener(eventhandle);
    circle1.setActionCommand("12");
    circle1.addMouseMotionListener(new MouseMotionAdapter(){});
             
   
    
    
    circle2 = new JMenuItem("Solid Oval");
    circle2.addActionListener(new ActionListener()
    {     public void actionPerformed(ActionEvent evt)
    { drawingStyle = 4;  
      drawPad.setDStyle(drawingStyle);}}
    );
    
    
    lines1 = new JMenuItem("Free-Hand");
    lines1.addActionListener(eventhandle);
    lines1.setActionCommand("10");
    lines1.addMouseMotionListener(new MouseMotionAdapter(){});
    
    lines2 = new JMenuItem("Line 2");
    lines2.addActionListener(eventhandle);
    lines2.setActionCommand("11");
    lines2.addMouseMotionListener(new MouseMotionAdapter(){});
    
    
    
    alpha1 = new JMenuItem("Letter 1");
    alpha2 = new JMenuItem("Letter 2");
    digit1 = new JMenuItem("Number 1");
    digit2 = new JMenuItem("Number 2");
    misc1 = new JMenuItem("Misc 1");
    misc2 = new JMenuItem("Misc 2");
    custom1 = new JMenuItem("Custom 1");
    custom2 = new JMenuItem("Custom 2"); 
	
	rectangles.add(rectangle1); 
	rectangles.add(rectangle2); 
	triangles.add(triangles1); 
	triangles.add(triangles2); 
	circle.add(circle1); 
	circle.add(circle2); 
	lines.add(lines1); 
	lines.add(lines2); 
	alpha.add(alpha1); 
	alpha.add(alpha2); 
	digit.add(digit1); 
	digit.add(digit2); 
	misc.add(misc1); 
	misc.add(misc2); 
	custom.add(custom1); 
	custom.add(custom2); 
	
	
	SideMenu.add(rectangles); 
	SideMenu.add(triangles); 
	SideMenu.add(circle); 
	SideMenu.add(lines); 
	SideMenu.add(alpha); 
	SideMenu.add(digit); 
	SideMenu.add(misc); 
	SideMenu.add(custom); 
} 

public LinearGUI() 
{ 
	init();
} 

public void init() 
{ 
	
eventhandle = new EventHandler();	
ordering = new Order();
Layer = new Drawing(firstColor);

JPanel StatusBar = new JPanel();
StatusBar.setBackground(ColorDesign);
StatusBar.setPreferredSize(new Dimension(640,40));
StatusBar.setBorder(BorderFactory.createLoweredBevelBorder());

JPanel HelpBar = new JPanel();
HelpBar.setBackground(ColorDesign);
HelpBar.setBorder(BorderFactory.createRaisedBevelBorder());
helptext = new JLabel("LinearGUI");
HelpBar.add(helptext);

JPanel InnerStatusBar = new JPanel(); 
InnerStatusBar.setBackground(ColorDesign);
InnerStatusBar.setBorder(BorderFactory.createRaisedBevelBorder()); 

Dimension dm = Toolkit.getDefaultToolkit().getScreenSize(); // Gets the screen size of the user's monitor 
double w = dm.width * .85; // 85% of the user's screen's width 
double h = dm.height * .85; // 85% of the user's screen's height 

JFrame guiFrame = new JFrame("LinearGUI"); // Creates a new window 

Container content = guiFrame.getContentPane(); 
content.setLayout(new BorderLayout()); 
  
DrawPanel = new CustomPanel();
DrawPanel.setBorder(BorderFactory.createLoweredBevelBorder());
DrawPanel.setBackground(Color.WHITE);
pointlocation = new Pointlocation();
pointlocation.setBackground(ColorDesign);

// JFrame Preferences 
 
guiFrame.setSize((int)w, (int)h); // Sets the x-length and y-length of the window, in pixels 
guiFrame.setResizable(false); // Disables the resizing of the JFrame 
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Ends the program with the "X" button is pressed 
guiFrame.setLayout(new GridLayout(3, 2)); 

createMenu(); //Creates the North Menu Bar (contains File Menu) 
createSideMenu(); //Creates the West Menu Bar (contains shapes) 

// Draw window 
guiFrame.setLayout(new BorderLayout()); 
guiFrame.add(SideMenu, BorderLayout.LINE_START); // Adds the Side Menu to the window 
guiFrame.add(StatusBar, BorderLayout.SOUTH); // Adds the coordinate panel to the window 
content.add(DrawPanel, BorderLayout.CENTER); // Adds the drawing pad to the window 
guiFrame.add(MainMenu, BorderLayout.NORTH); // Adds the Main Menu to the window 

InnerStatusBar.add(pointlocation);
StatusBar.setLayout(new BorderLayout());
StatusBar.add(HelpBar, BorderLayout.CENTER);
StatusBar.add(InnerStatusBar, BorderLayout.EAST);

guiFrame.setVisible(true); // Makes the window visible
}
class HorizontalMenu extends JMenu 
{ 
	HorizontalMenu(String label) 
	{ 
	super(label); 
	JPopupMenu pm = getPopupMenu(); 
	pm.setLayout(new BoxLayout(pm, BoxLayout.LINE_AXIS)); 
	} 

	public Dimension getMinimumSize() 
	{ 
	return getPreferredSize(); 
	} 

	public Dimension getMaximumSize() 
	{ 
	return getPreferredSize(); 
	} 

	public void setPopupMenuVisible(boolean b) 
	{ 
		boolean isVisible = isPopupMenuVisible(); 
		if (b != isVisible) 
		{ 
			if ((b==true) && isShowing()) 
			{ 
				//Set location of popupMenu (pulldown or pullright). 
				//Perhaps this should be dictated by L&F. 
				int x = 0; 
				int y = 0; 
				Container parent = getParent(); 
				if (parent instanceof JPopupMenu) 
				{ 
					x = 0; 
					y = getHeight(); 
				} 
				else 
				{ 
					x = getWidth(); 
					y = 0; 
				} 
					getPopupMenu().show(this, x, y); 
			} 
			else 
			{ 
					getPopupMenu().setVisible(false); 
			} 
		} 
	} 
} 
class Pointlocation extends JPanel
{
	JLabel locationX = new JLabel("",SwingConstants.RIGHT);
	JLabel locationY = new JLabel("",SwingConstants.RIGHT);
	public Pointlocation()
	{
		setBorder(BorderFactory.createLoweredBevelBorder());
		setPreferredSize(new Dimension(130,25));
		add(locationX);
		add(locationY);
	}

	public void setPointX(int x)
	{
		locationX.setText("(x=" + x + ",");
	}
	
	public void setPointY(int y)
	{
		locationY.setText(" y=" + y + ")");
	}
}

public class CustomPanel extends JPanel implements MouseInputListener
{

	public CustomPanel()
	{
		addMouseListener(this);
		addMouseMotionListener(this);
	}
	
	public void paint(Graphics g)
	{
		super.paint(g);
		Layer.draw(g);
	}
	
	public void mouseClicked(MouseEvent event)
	{
		if(!(event.isMetaDown()) && !(event.isAltDown()))
		{	
		eventhandle.ordering.mouseClickExe(event.getPoint(), Layer);
		repaint();
		}
	}
	
	public void mousePressed(MouseEvent event)
	{
		if (!(event.isMetaDown()) && !(event.isAltDown()))
		{
		eventhandle.ordering.mousePressExe(event.getPoint(), Layer);
			repaint();
		}
	}
	
	public void mouseDragged(MouseEvent event)
	{
		
		
		if (!(event.isMetaDown()) && !(event.isAltDown()) && event.isShiftDown())
		{
				eventhandle.ordering.mouseDragShiftExe(event.getPoint(), Layer); 
	   			repaint();
		}
		else if (!(event.isMetaDown()) && !(event.isAltDown()))
		{
		    eventhandle.ordering.mouseDragExe(event.getPoint(), Layer, object1);
			repaint();
		}
		pointlocation.setPointX(event.getX());	
		pointlocation.setPointY(event.getY());	
	}
	
	public void mouseMoved(MouseEvent event) 
		{
		pointlocation.setPointX(event.getX());	
		pointlocation.setPointY(event.getY());	
			
		} 
	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	
	
}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	} 
public static void main(String[] args) 
	{ 
		LinearGUI gui = new LinearGUI(); 
	}
} 

